from no_6.models import RBACUser, RBACPermission, RBACRole
import re
from django.shortcuts import HttpResponse
from django.utils.deprecation import MiddlewareMixin


def initial_permission(user, request):
    # 查询角色
    ret = user.role.all()
    print(ret)  # <QuerySet [<Role: 人力资源总监>]>
    # 查询角色所对应的权限
    re = user.role.all().values('permission__url')
    print(re)  # <QuerySet [{'permission__url': '/users/'}]>
    permission_list = []
    for item in re:
        permission_list.append(item["permission__url"])
    print(permission_list)  # ['/users/']
    request.session["permission_list"] = permission_list

    # # 查询角色
    # ret = user.role.all()
    # # print(ret)#<QuerySet [<Role: 人力资源总监>]>
    # # 查询角色所对应的权限
    # permission_list = []
    # for item1 in ret:
    #     # 多对多连表查询
    #     rep = RBACPermission.objects.filter(role__title=item1)
    #     for item2 in rep:
    #         # print(item2.url)#/users/
    #         permission_list.append(item2.url)
    # # print(permission_list)
    # request.session["permission_list"] = permission_list


class ValidPermission(MiddlewareMixin):
    """
    权限验证中间件类
    """

    # 为了防止中间件影响simple和rbac的代码逻辑，这里都return None，不校验
    # 要尝试效果可自己放开注释
    def process_request(self, request):
        # ######################中间件内容start###############
        # # 获取session键值，如果不存在不报错，返回[]
        # permission_list = request.session.get('permission_list', [])
        # # print(permission_list)
        # path = request.path_info
        # print(path)
        # # flag = False
        # # for permission in permission_list:
        # #     permission = "^%s$" % permission
        # #     ret = re.match(permission, path)
        # #     if ret:
        # #         flag = True
        # #         break
        # # # print(flag)
        # # if not flag:
        # #     return HttpResponse('无访问权限！')
        #
        # # 只校验no_6应用的url
        # if not path.startswith('/no_6/'):
        #     return None
        #
        # # 查看是否属于白名单
        # valid_url_list=['/login/', '/admin/.*']
        # # for valid_url in valid_url_list:
        # #     ret=re.match(valid_url,path)
        # #     if ret:
        # #         return None
        # if filter(lambda item: re.match(item, path), valid_url_list):
        #     return None
        #
        # if not filter(lambda item: item == path, permission_list):
        #     return HttpResponse('无访问权限！')
        # ##################中间件内容end###################
        return None
